let editType = '';
let isTimer = false;
let isConnected = false; // 是否已经连接
let isTest = false;

let powerDom ;
let dischargeStatusDom;
let batteryVoltageDom ;
let usbVoltageDom;
let capacitorVoltageDom;
let capacitanceTemperatureDom;

let chargeProtectDom;
let chargingSpeedDom;
let cutOffVoltageDom;
let lightEnableDom
let lightStatusDom;
let lightBrightnessDom;

let dischargeModeDom;
let usedModeDom;
let autoDischargeSensitivityDom;
let carDischargeSensitivityDom;
let sosDom;

let autoDischargeBtn;
let timerDischargeBtn;
let manuallyDischargeBtn;
let offDischargeBtn;
let offBtn;

let editContainer = document.getElementById('edit-container');
let editPanelTitle;
let editPanelContentInput;
let editPanelContentSelect;

let containerDom = document.getElementById('container');
let connectDom = document.getElementById('connect');

let waitingDom;
let waitingTimerDom;

let testDataInput;

const blueToothUtil = new BlueToothUtil(() => {
    alert('蓝牙设备已断开连接');
    closeConnect();
});
async function connect() {
    if(isConnected) {
        return;
    }

    const res = await connectBlueTooth();
    if(!res) {
        return;
    }
    connected();
}

function connected() {
    isConnected = true;

    powerDom = document.getElementById('power');
    dischargeStatusDom = document.getElementById('discharge-status');
    batteryVoltageDom = document.getElementById('battery-voltage');
    usbVoltageDom = document.getElementById('usb-status');
    capacitorVoltageDom = document.getElementById('capacitor-voltage');
    capacitanceTemperatureDom = document.getElementById('capacitance-temperature');

    chargeProtectDom = document.getElementById('discharge-protection');
    chargingSpeedDom = document.getElementById('charging-speed');
    cutOffVoltageDom = document.getElementById('cut-off-voltage');
    lightEnableDom = document.getElementById('light-enable');
    lightStatusDom = document.getElementById('light-status');
    lightBrightnessDom = document.getElementById('light-brightness');

    dischargeModeDom = document.getElementById('discharge-mode');
    usedModeDom = document.getElementById('used-mode');
    autoDischargeSensitivityDom = document.getElementById('auto-discharge-sensitivity');
    carDischargeSensitivityDom = document.getElementById('car-discharge-sensitivity');
    sosDom = document.getElementById('sos');

    autoDischargeBtn = document.getElementById('auto-discharge-btn');
    timerDischargeBtn = document.getElementById('timer-discharge-btn');
    manuallyDischargeBtn = document.getElementById('manually-discharge-btn');
    offDischargeBtn = document.getElementById('off-discharge-btn');
    offBtn = document.getElementById('off-btn');

    editContainer = document.getElementById('edit-container');
    editPanelTitle = document.getElementById('edit-panel-title');
    editPanelContentInput = document.getElementById('edit-panel-content-input');
    editPanelContentSelect = document.getElementById('edit-panel-content-select');

    containerDom = document.getElementById('container');
    connectDom = document.getElementById('connect');

    waitingDom = document.getElementById('waiting');
    waitingTimerDom = document.getElementById('waiting-timer');

    testDataInput = document.getElementById('test-data');

    containerDom.style.display = 'flex';
    connectDom.style.display = 'none';
}

async function connectBlueTooth() {
    let res = false;
    try {
        await blueToothUtil.request();
        await blueToothUtil.connect();

        await blueToothUtil.startOrderNotifications(data => {
            const decoder = new TextDecoder('utf-8');
            const value =  decoder.decode(data.target.value);
            showData(value);
            console.log(value);
        })
        return true;
    } catch(error) {
        console.error(error);
    }
    return res;
}

async function disconnect() {
    console.log('断开连接');
    if (!isConnected) {
        return;
    }
    await blueToothUtil.disconnect();
    closeConnect();
}

function closeConnect() {
    isConnected = false;
    editContainer.style.display = 'none';
    containerDom.style.display = 'none';
    connectDom.style.display = 'flex';
}



function init() {
    closeConnect();

    if (isTest) {
        connected();
        testDataInput.style.display = 'block';
        setInterval(() => {
            const data = testDataInput.value;
            showData(data);
        }, 500);
    } else {
        if (!('bluetooth' in navigator)) {
            connectDom.innerHTML = '抱歉，您的浏览器不支持蓝牙连接，请使用谷歌（Chrome）或Edge浏览器访问该页面。';
        }
    }
}

function showData(value) {
    const data = value.split('-');
    if (data.length !== 19) return;

    const autoFlag = parseInt(data[15]);
    const timerFlag = parseInt(data[16]);
    if (timerFlag === 0) {
        isTimer = false;
    }

    // 电池电压
    const batteryVoltage = parseFloat(data[0]);
    batteryVoltageDom.children[0].children[0].innerHTML = batteryVoltage.toFixed(1);
    if (batteryVoltage > 30.0) {
        batteryVoltageDom.classList.add('orange');
        batteryVoltageDom.classList.remove('green');
    } else {
        if (batteryVoltage <= 0.5) {
            batteryVoltageDom.children[0].children[0].innerHTML = '--';
        }
        batteryVoltageDom.classList.remove('orange');
        batteryVoltageDom.classList.add('green');
    }

    // USB电压
    const usbVoltage = parseFloat(data[1]);
    if (usbVoltage > 3.5) {
        batteryVoltageDom.children[0].children[0].innerHTML = '--';
        usbVoltageDom.children[0].children[0].innerHTML = usbVoltage.toFixed(1);
    } else if (usbVoltage < 3.5) {
        usbVoltageDom.children[0].children[0].innerHTML = '--';
    } else {
        usbVoltageDom.children[0].children[0].innerHTML = '3.5'
    }

    // 电容电压
    const capacitorVoltage = parseFloat(data[2]);
    capacitorVoltageDom.children[0].children[0].innerHTML = capacitorVoltage.toFixed(1);

    // 电容温度
    const capacitanceTemperature = parseFloat(data[3]);
    capacitanceTemperatureDom.children[0].children[0].innerHTML = capacitanceTemperature.toFixed(1);
    if (capacitanceTemperature > 90.0) {
        capacitanceTemperatureDom.classList.add('orange');
        capacitanceTemperatureDom.classList.remove('green');
    } else {
        capacitanceTemperatureDom.classList.add('green');
        capacitanceTemperatureDom.classList.remove('orange');
    }

    // 充电速度
    const chargingSpeed = parseInt(data[4]);
    chargingSpeedDom.setAttribute('data-value', chargingSpeed.toFixed(0));
    chargingSpeedDom.children[0].children[0].innerHTML = chargingSpeed.toFixed(0);

    // 截止电压
    const cutOffVoltage = parseFloat(data[5]);
    cutOffVoltageDom.setAttribute('data-value', cutOffVoltage.toFixed(1));
    cutOffVoltageDom.children[0].children[0].innerHTML = cutOffVoltage.toFixed(1);

    // 照明亮度
    const lightBrightness = parseInt(data[6]);
    lightBrightnessDom.setAttribute('data-value', lightBrightness.toFixed(0));
    lightBrightnessDom.children[0].children[0].innerHTML = lightBrightness.toFixed(0);

    // 放电模式
    const dischargeMode = parseInt(data[10]);
    dischargeModeDom.setAttribute('data-value', dischargeMode.toFixed(0));
    if (dischargeMode === 2) {
        dischargeModeDom.children[0].children[0].innerHTML = '全手动';
    } else if (dischargeMode === 1) {
        dischargeModeDom.children[0].children[0].innerHTML = '无电瓶';
    } else {
        dischargeModeDom.children[0].children[0].innerHTML = '有电瓶';
    }

    // 用途模式
    const usedMode = parseInt(data[11]);
    usedModeDom.setAttribute('data-value', usedMode.toFixed(0));
    if (usedMode > 0) {
        usedModeDom.children[0].children[0].innerHTML = '车载稳压';
    } else {
        usedModeDom.children[0].children[0].innerHTML = '应急救援';
    }

    // 自动放电灵敏度
    const autoDischargeSensitivity = parseInt(data[12]);
    autoDischargeSensitivityDom.setAttribute('data-value', autoDischargeSensitivity.toFixed(0));
    autoDischargeSensitivityDom.children[0].children[0].innerHTML = autoDischargeSensitivity.toFixed(0);

    // 车载放电灵敏度
    const carDischargeSensitivity = parseInt(data[13]);
    carDischargeSensitivityDom.setAttribute('data-value', carDischargeSensitivity.toFixed(0));
    if ([0,1].includes(carDischargeSensitivity)) {
        carDischargeSensitivityDom.children[0].children[0].classList.remove('size40');
        carDischargeSensitivityDom.children[0].children[0].classList.add('size20');
        carDischargeSensitivityDom.children[0].children[1].innerHTML = "";
    } else {
        carDischargeSensitivityDom.children[0].children[0].classList.remove('size20');
        carDischargeSensitivityDom.children[0].children[0].classList.add('size40');
        carDischargeSensitivityDom.children[0].children[1].innerHTML = "级";
    }
    carDischargeSensitivityDom.children[0].children[0].innerHTML = carDischargeSensitivity === 0 ? '点火接通' :
        (carDischargeSensitivity === 1 ? "等压接通" : (carDischargeSensitivity-1).toFixed(0));

    // 电量
    const power = parseInt(data[14]);
    powerDom.children[0].children[0].innerHTML = power.toFixed(0);


    // 放电状态
    const dischargeStatus = parseInt(data[8]);
    if (dischargeStatus === 1) {
        dischargeStatusDom.classList.remove('gray');
        dischargeStatusDom.classList.add('green');
        dischargeStatusDom.children[0].children[0].innerHTML = 'ON';
        waitingDom.style.display = 'none';
    } else {
        dischargeStatusDom.classList.remove('green');
        dischargeStatusDom.classList.add('gray');
        dischargeStatusDom.children[0].children[0].innerHTML = 'OFF';

        if ((autoFlag === 1 || timerFlag === 1)) {
            waitingDom.style.display = 'inline-block';
            if (timerFlag === 1) {

            }
        } else {
            waitingDom.style.display = 'none';
        }
    }


    // 放电可用
    const chargeProtect = parseInt(data[9]);
    if (chargeProtect === 1) {
        chargeProtectDom.classList.remove('green');
        chargeProtectDom.classList.add('orange');
        chargeProtectDom.children[0].children[0].innerHTML = 'OFF';
    } else {
        chargeProtectDom.classList.remove('orange');
        chargeProtectDom.classList.add('green');
        chargeProtectDom.children[0].children[0].innerHTML = 'ON';
    }

    // 照明状态
    const lightEnable = parseInt(data[17]);
    lightEnableDom.setAttribute('data-value', lightEnable.toFixed(0));
    if (lightEnable === 1) {
        lightEnableDom.classList.remove('grey');
        lightEnableDom.classList.add('light-green');
        lightEnableDom.children[0].children[0].innerHTML = 'ON';
    } else {
        lightEnableDom.classList.remove('light-green');
        lightEnableDom.classList.add('grey');
        lightEnableDom.children[0].children[0].innerHTML = 'OFF';
    }

    // SOS
    const sos = parseInt(data[18]);
    if (sos === 1) {
        sosDom.classList.remove('grey');
        sosDom.classList.add('light-green');
        sosDom.children[0].children[0].innerHTML = 'ON';
    } else {
        sosDom.classList.remove('light-green');
        sosDom.classList.add('grey');
        sosDom.children[0].children[0].innerHTML = 'OFF';
    }

    // 照明开关
    const lightStatus = parseInt(data[7]);
    if (lightEnable === 0 || sos === 1) {
        lightStatusDom.classList.remove('light-green');
        lightStatusDom.classList.remove('grey');
        lightStatusDom.classList.add('disabled');
        lightStatusDom.children[0].children[0].innerHTML = 'OFF';
    } else {
        lightStatusDom.classList.remove('disabled');
        if (lightStatus === 1) {
            lightStatusDom.classList.remove('grey');
            lightStatusDom.classList.add('light-green');
            lightStatusDom.children[0].children[0].innerHTML = 'ON';
        } else {
            lightStatusDom.classList.remove('light-green');
            lightStatusDom.classList.add('grey');
            lightStatusDom.children[0].children[0].innerHTML = 'OFF';
        }
    }

    // 放电按钮
    if (dischargeStatus === 1 || usedMode === 1 || chargeProtect === 1 || timerFlag === 1 || autoFlag === 1) {
        autoDischargeBtn.classList.add('disabled');
        autoDischargeBtn.classList.remove('blue');
        autoDischargeBtn.setAttribute('data-value', '0');

        timerDischargeBtn.classList.add('disabled');
        timerDischargeBtn.classList.remove('blue');
        timerDischargeBtn.setAttribute('data-value', '0');

        manuallyDischargeBtn.classList.add('disabled');
        manuallyDischargeBtn.classList.remove('blue');
        manuallyDischargeBtn.setAttribute('data-value', '0');
    } else {
        // 手动放电按钮状态
        if ([1,0].includes(dischargeMode)) {
            manuallyDischargeBtn.classList.add('disabled');
            manuallyDischargeBtn.classList.remove('blue');
            manuallyDischargeBtn.setAttribute('data-value', '0');
        } else {
            manuallyDischargeBtn.classList.remove('disabled');
            manuallyDischargeBtn.classList.add('blue');
            manuallyDischargeBtn.setAttribute('data-value', '1');
        }

        // 自动放电按钮状态
        if ([1,2].includes(dischargeMode)) {
            autoDischargeBtn.classList.add('disabled');
            autoDischargeBtn.classList.remove('blue');
            autoDischargeBtn.setAttribute('data-value', '0');
        } else {
            autoDischargeBtn.classList.remove('disabled');
            autoDischargeBtn.classList.add('blue');
            autoDischargeBtn.setAttribute('data-value', '1');
        }

        // 倒计时放电按钮状态
        if ([2].includes(dischargeMode)) {
            timerDischargeBtn.classList.add('disabled');
            timerDischargeBtn.classList.remove('blue');
            timerDischargeBtn.setAttribute('data-value', '0');
        } else {
            timerDischargeBtn.classList.remove('disabled');
            timerDischargeBtn.classList.add('blue');
            timerDischargeBtn.setAttribute('data-value', '1');
        }
    }

    // 关闭放电按钮状态
    if ((dischargeStatus === 0 && timerFlag === 0 && autoFlag === 0) || usedMode === 1) {
        offDischargeBtn.classList.add('disabled');
        offDischargeBtn.classList.remove('blue');
        offDischargeBtn.setAttribute('data-value', '0');
    } else {
        offDischargeBtn.classList.remove('disabled');
        offDischargeBtn.classList.add('blue');
        offDischargeBtn.setAttribute('data-value', '1');
    }

    // 关机按钮状态
    if (batteryVoltage > 1.0) {
        offBtn.classList.add('disabled');
        offBtn.classList.remove('blue');
        offBtn.setAttribute('data-value', '0');
    } else {
        offBtn.classList.remove('disabled');
        offBtn.classList.add('blue');
        offBtn.setAttribute('data-value', '1');
    }
}

async function writeData(value) {
    console.log('writeData', value);
    if(!isConnected) {
        return;
    }
    const byteArray = new TextEncoder().encode(value);
    const buffer = byteArray.buffer;
    await blueToothUtil.writeOrder(buffer);
    // console.log('writeData', value);
    // const data = testDataInput.value.split('-')
    // if (data.length !== 19) return;
    // const values = value.split('-');
    // switch (values[0]) {
    //     case '01':
    //         data[7] = data[7] === '0' ? '1' : '0';
    //         break;
    //     case '02':
    //         data[8] = 0;
    //         data[15] = 1;
    //         break;
    //     case '03':
    //         data[8] = 0;
    //         data[16] = 1;
    //         break;
    //     case '04':
    //         data[8] = 1;
    //         break;
    //     case '05':
    //         data[8] = 0;
    //         data[15] = 0;
    //         data[16] = 0;
    //         break;
    //     case '06':
    //         data[10] = values[1].substring(2, 3);
    //         break;
    //     case '07':
    //         data[11] = values[1].substring(2, 3);
    //         break;
    //     case '08':
    //         data[4] = values[1];
    //         break;
    //     case '09':
    //         data[6] = values[1];
    //         break;
    //     case '10':
    //         data[5] = (values[1]/10).toFixed(1);
    //         break;
    //     case '11':
    //         data[12] = values[1].substring(2, 3);
    //         break;
    //     case '12':
    //         data[13] = values[1].substring(2, 3);
    //         break;
    //     case '14':
    //         data[17] = values[1] === '001' ? '1' : '0';
    //         break;
    //     case '15':
    //         data[18] = data[18] === '0' ? '1' : '0';
    //         break;
    //     default:
    //         break;
    // }
    // testDataInput.value = data.join('-');
}

function changeLightEnable() {
    const value = parseInt(lightEnableDom.getAttribute('data-value'));
    if (value === 1) {
        writeData('14-000');
    } else {
        writeData('14-001');
    }
}

function changeLightStatus() {
    const value = parseInt(lightEnableDom.getAttribute('data-value'));
    if (value === 0) {
        return;
    }
    writeData('01-001');
}

function changeSos() {
    writeData('15-001');
}

function showEditContainer(type) {
    const isShow = editContainer.style.display === 'none';
    if (isShow) {
        editType = type;
        editPanelContentSelect.style.display = 'none';
        editPanelContentSelect.replaceChildren();
        editPanelContentInput.style.display = 'none';
        switch (type) {
            case 'charging-speed':
                editPanelTitle.innerHTML = '编辑充电速度';
                editPanelContentInput.value = chargingSpeedDom.getAttribute('data-value');
                editPanelContentInput.style.display = 'flex';
                break;
            case 'cut-off-voltage':
                editPanelTitle.innerHTML = '编辑截止电压';
                editPanelContentInput.value = cutOffVoltageDom.getAttribute('data-value');
                editPanelContentInput.style.display = 'flex';
                break;
            case 'light-brightness':
                editPanelTitle.innerHTML = '编辑照明亮度';
                editPanelContentInput.value = lightBrightnessDom.getAttribute('data-value');
                editPanelContentInput.style.display = 'flex';
                break;
            case 'auto-discharge-sensitivity':
                editPanelTitle.innerHTML = '编辑自动放电灵敏度';
                editPanelContentSelect.style.display = 'flex';
                for (let i = 1; i < 10; i++) {
                    editPanelContentSelect.appendChild(new Option(`${i}级灵敏度`, i.toString()));
                }
                editPanelContentSelect.value = autoDischargeSensitivityDom.getAttribute('data-value');
                break;
            case 'car-discharge-sensitivity':
                editPanelTitle.innerHTML = '编辑车载放电灵敏度';
                editPanelContentSelect.style.display = 'flex';
                for (let i = 0; i < 11; i++) {
                    if (i === 0) {
                        editPanelContentSelect.appendChild(new Option(`点火接通`, i.toString()));
                    } else if (i === 1) {
                        editPanelContentSelect.appendChild(new Option(`等压接通`, i.toString()));
                    } else {
                        editPanelContentSelect.appendChild(new Option(`${i-1}级灵敏度`, i.toString()));
                    }
                }
                editPanelContentSelect.value = carDischargeSensitivityDom.getAttribute('data-value');
                break;
            case 'discharge-mode':
                editPanelTitle.innerHTML = '编辑放电模式';
                editPanelContentSelect.style.display = 'flex';
                editPanelContentSelect.appendChild(new Option(`有电瓶`, '0'));
                editPanelContentSelect.appendChild(new Option(`无电瓶`, '1'));
                editPanelContentSelect.appendChild(new Option(`全手动`, '2'));
                editPanelContentSelect.value = dischargeModeDom.getAttribute('data-value');
                break;
            case 'used-mode':
                editPanelTitle.innerHTML = '编辑用途模式';
                editPanelContentSelect.style.display = 'flex';
                editPanelContentSelect.appendChild(new Option(`应急救援`, '0'));
                editPanelContentSelect.appendChild(new Option(`车载稳压`, '1'));
                editPanelContentSelect.value = usedModeDom.getAttribute('data-value');
                break;
        }
        editContainer.style.display = 'flex';
    } else {
        editType = '';
        editContainer.style.display = 'none';
    }
}

async function submitButton(dom, value) {
    const dataValue = parseInt(dom.getAttribute('data-value'));
    if (dataValue === 0) {
        return;
    }
    await writeData(value);
    if (value === '03-001') {
        disTimerInterval();
    }
    if (value === '13-001') {
        offBtn.classList.add('disabled');
        offBtn.classList.remove('blue');
        offBtn.setAttribute('data-value', '0');
    }
}

// 倒计时放电显示
function disTimerInterval() {
    if (isTimer) {
        return;
    }
    isTimer = true;
    let timerText = 10;
    waitingTimerDom.innerHTML = timerText.toString();
    const timer = setInterval(() => {
        timerText--;
        if (timerText < 0 || !isTimer ) {
            clearInterval(timer);
            timerText = -1;
            waitingTimerDom.innerHTML = '';
        } else {
            waitingTimerDom.innerHTML = timerText.toString()
        }
    }, 1000);
}

function submitData() {
    if (editType === '') {
        return;
    }
    let value = editPanelContentInput.value;
    let value2 = editPanelContentSelect.value;
    let orderValue = '';
    switch (editType) {
        case 'discharge-mode':
            value = parseInt(value2);
            orderValue = '06-00' + value;
            break;
        case 'used-mode':
            value = parseInt(value2);
            orderValue = '07-00' + value;
            break;
        case 'charging-speed':
            value = parseInt(value);
            if (isNaN(value) || value < 0 || value > 100) {
                alert('充电速度必须在0~100之间');
                return;
            }
            orderValue = '08-';
            if (value < 10) {
                orderValue += '00' + value;
            } else if (value < 100) {
                orderValue += '0' + value;
            } else {
                orderValue += '100';
            }
            break;
        case 'light-brightness':
            value = parseInt(value);
            if (isNaN(value) || value < 1 || value > 100) {
                alert('灯光亮度必须在1~100之间');
                return;
            }
            orderValue = '09-';
            if (value < 10) {
                orderValue += '00' + value;
            } else if (value < 100) {
                orderValue += '0' + value;
            } else {
                orderValue += '100';
            }
            break;
        case 'cut-off-voltage':
            value = parseFloat(value);
            if (isNaN(value) || value < 0 || value > 15.0) {
                alert('截止电压必须在0.0~15.0之间');
                return;
            }
            orderValue = '10-';
            if (value < 1.0) {
                orderValue += '00' + (value*10).toFixed(0);
            } else if (value < 10.0) {
                orderValue += '0' + (value*10).toFixed(0);
            } else {
                orderValue += (value*10).toFixed(0);
            }
            break;

        case 'auto-discharge-sensitivity':
            value = parseInt(value2);
            orderValue = '11-00' + value;
            break;
        case 'car-discharge-sensitivity':
            value = parseInt(value2);
            orderValue = '12-0' + (value > 9 ? value.toString() : '0' + value.toString());
            break;

    }
    if (orderValue) writeData(orderValue);
    showEditContainer();
}